/*
 * Copyright 2025 arisgo@163.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.arisgo.cloud.flux.filter;

import com.arisgo.cloud.core.redis.UserInfo;
import com.arisgo.cloud.core.url.UrlProperties;
import com.arisgo.cloud.core.utils.JwtUtil;
import com.arisgo.cloud.flux.utils.ExchangeUtil;
import com.auth0.jwt.RegisteredClaims;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import static org.springframework.http.HttpStatus.UNAUTHORIZED;

/**
 * @author Arisgo
 * @since 2024/6/10
 */
@Component
@AllArgsConstructor
public class LoginFilter implements WebFilter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final UrlProperties urlProperties;
    private final RedisTemplate<String, Object> redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (urlProperties.isSkipUrl(path)) {
            logger.info("request path: {}", path);
            return chain.filter(exchange);
        }
        // 登陆验证
        String authorization = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        UserInfo user = (UserInfo) redisTemplate.opsForValue().get(JwtUtil.getClaim(authorization, RegisteredClaims.AUDIENCE, String.class));
        if (null == user) {
            return ExchangeUtil.sendResponseError(exchange, UNAUTHORIZED);
        }
        exchange.getAttributes().put("userId", user.getUserId());
        exchange.getAttributes().put("username", user.getUsername());
        return chain.filter(exchange);
    }

}
